﻿

import Request from "../../base/request.js?t=202511041006"
import Storage from "../../base/storage.js?t=202511041006"
import { imageBaseUrl, downloadfun, isImageFile, queryURLParams, getBrowserInfo } from "../../base/utils.js?t=202511041006"
const Composition = (proxy) => {


    const data = reactive({
        pdfOpen: false,
        pdfurl: "",

        areaList: [
            { label: '浦东', value: 1 },
            { label: '大场', value: 2 },
        ],

        checkPersonList: [

        ],
        shadowShow: true,
        urlparams: {},
        messageTest: "",
        proxy: "",
        popShow: false,
        popTitle: '',
        imgUrl: "",
        previewShow: false,
        detailColumns: [
            {
                title: '序号',
                dataIndex: 'no',
                key: 'no',
                align: 'center',
                width: 80,
                customRender: ({ index }) => {
                    return (params.detailPagination.value.current - 1) * params.detailPagination.value.pageSize + index + 1
                },
            },
            {
                title: '姓名',
                dataIndex: 'name',
                key: 'name',
                align: 'center',
                customRender: ({ record }) => {
                    return `${record.name}(${record.code})`
                },


            },

            {
                title: '申请数量',
                dataIndex: 'number',
                key: 'number',
                align: 'center',

            },
            {
                title: '操作',
                dataIndex: 'StatusName',
                key: 'StatusName',
                align: 'center',
                width: '100px',
                customRender: ({ record, text }) => {
                    return h(antd.Button, {
                        color: "red",
                        onClick: () => {
                            methods.handleDeleteItem(record.code)
                        },
                        style: 'cursor:pointer'
                    }, { default: () => '删除' });
                },

            }
        ],
        detailDataSource: [],
        editInfoOptions: [],
        detailPagination: {
            total: 0,
            current: 1,
            loading: false,
            pageSize: 10,
            showTotal: total => `总共 ${total} 项`,
            defaultPageSize: 10,
            showSizeChanger: true, // 是否显示pagesize选择
            showQuickJumper: false, // 是否显示跳转窗
        },
        TypeId: null,
        editInfo: [{

            a: null,
            b: null,
            c: null,
            e: null,
            ceditInfoOptions: {},
            EmployeeList: []

        }],
        cindex: 0,
        templateOpen: false,
        opType: 0,
        uploadImg: {
            previewVisible: false,
            previewImage: "",
            previewTitle: "",
            fileList: [

            ]
        },
        itemRender: (data) => {

            let uid = data.file.uid
            const previewBtn = h('img', { style: 'cursor:pointer;margin:0 4px;', onclick: () => { methods.btnPreview(uid) }, src: "../Bussiness/img/svg/preview.svg", width: 20, height: 22 }, { default: () => '预览' })
            const downloadBtn = h('img', { style: 'cursor:pointer;margin:0 4px;', onclick: () => { methods.btnDownLoad(uid) }, src: "../Bussiness/img/svg/download.svg", width: 20, height: 22 }, { default: () => '下载' })
            const deleteBtn = h('img', { style: 'cursor:pointer;margin:0 4px;', onclick: () => { methods.btnDelete(uid) }, src: "../Bussiness/img/svg/delete.svg", width: 18, height: 22 }, { default: () => '删除' })
            var btns = ""


            if (isImageFile(data.file.url)) {


                btns = h('div', { style: "display:flex;margin-left:10px" }, {
                    default: () => [
                        previewBtn,
                        downloadBtn,
                        deleteBtn
                    ]
                })

            } else {


                btns = h('div', { style: "display:flex;margin-left:10px" }, {
                    default: () => [
                        downloadBtn,
                        deleteBtn
                    ]
                })
            }

            return h('div', { style: 'margin-top:10px; width:400px;align-items:center; display:flex;justify-content:space-between' }, {
                default: () => [
                    data.file.name, btns
                ]
            })

        },
        addParams: {
            name: null,
            code: null,
            number: null,
        },
        uploadLock: false,
        configData: {
            name1: "",
            name2: "",
            name3: "",
            name4: "",
            name5: "",
            FactoryAreaId: 1,
            checkPersonId: null
        },

        baseInfo: {

        },
        sAttrList:[],
        settingList: []

    })
    let params = toRefs(data)
    const methods = {
        setVisible: (value) => {
            params.previewShow.value = value;
        },
        handleDeleteItem: (code) => {
            params.detailDataSource.value = params.detailDataSource.value.filter(e => e.code != code)
            params.editInfo.value[params.cindex.value].EmployeeList = params.editInfo.value[params.cindex.value].EmployeeList.filter(e => e.EmployeeNo != code)
            params.detailPagination.value.total = params.detailDataSource.value.length
            params.editInfo.value[params.cindex.value].e = methods.sumData(params.editInfo.value[params.cindex.value].EmployeeList)
        },
        clearData: () => {
            params.detailDataSource.value = []
            params.detailPagination.value.total = 0
            params.editInfo.value[params.cindex.value].EmployeeList = params.detailDataSource.value
            params.editInfo.value[params.cindex.value].e = 0
        },
        btnPreview: (e) => {
            let item = params.uploadImg.value.fileList.find(es => es.uid == e)
            item.url = item.FilePath || item.url
            if (item.url.indexOf('.pdf') != -1) {
                params.pdfurl.value = item.url
                params.pdfOpen.value = true
            } else {
                params.imgUrl.value = item.url
                methods.setVisible(true)
            }
        },
        btnDownLoad: (e) => {
            let item = params.uploadImg.value.fileList.find(es => es.uid == e)
            item.url = item.FilePath || item.url
            if (item.url.indexOf('.pdf') != -1) {
                params.pdfurl.value = item.url
                params.pdfOpen.value = true
            } else {
                params.imgUrl.value = item.url
                methods.setVisible(true)
            }

        },
        btnDelete: (e) => {
            params.uploadImg.value.fileList = params.uploadImg.value.fileList.filter(es => es.uid != e)
        },
        scrollt: () => {
            setTimeout(() => {
                // 判断是否滚动到底部
                if (params.proxy.value.$refs.scrollt.scrollTop + params.proxy.value.$refs.scrollt.clientHeight >= params.proxy.value.$refs.scrollt.scrollHeight) {
                    params.shadowShow.value = false
                } else {
                    params.shadowShow.value = true
                }
            }, 400)

        },
        handleChange: (info) => {

            if (!params.uploadLock.value) {
                params.uploadLock.value = true
                let formData = new FormData();
                formData.append('nfile', info.file.originFileObj)
                formData.append('uid', info.file.originFileObj.uid)
                Request({
                    url: "/download/uploadfile?Path=PPE/Apply",
                    method: 'post',
                    data: formData
                }).then(res => {

                    let item = params.uploadImg.value.fileList.find(e => e.uid == res.Data[0].uid)
                    item.url = imageBaseUrl + res.Data[0].FilePath.split('../..')[1]
                    item.FileId = res.Data[0].FileId
                    item.FileName = res.Data[0].FileName
                    item.name = res.Data[0].FileName
                    params.uploadLock.value = false


                })
            }



        },

        handlePopOk: () => {

            if (params.opType.value == 0) {

                params.editInfo.value[params.cindex.value].EmployeeList.push({
                    EmployeeNo: params.addParams.value.code,
                    EmployeeName: params.addParams.value.name,
                    Quantity: params.addParams.value.number,
                })
                params.editInfo.value[params.cindex.value].e = methods.sumData(params.editInfo.value[params.cindex.value].EmployeeList)
                params.addParams.value = {
                    name: null,
                    code: null,
                    number: null
                }
            } else {

            }

            params.popShow.value = false
        },
        handleSTypeChange: (a, b, c) => {

            let label = params.editInfo.value[b].AttrList[c].ItemList.filter(es => es.Id == a)[0].AttributeValue
            params.editInfo.value[b].AttrList[c].SelectLabel = label


        },
        handleTypeChange: (c, d) => {

        },
        handleAdd: (i) => {
            params.opType.value = 0
            params.cindex.value = i
            params.popShow.value = true
            params.popTitle.value = `新增人员申请`
        },

        handleView: (e, i) => {

            if (!e.alabel || e.AttrList.filter(es => es.SelectLabel).length !== e.AttrList.length) {
                return params.messageTest.value.info('请先选择劳防用品和规格');
            }
            params.opType.value = 1
            params.popShow.value = true
            params.popTitle.value = `${e.alabel}(${e.AttrList.map(es => es.SelectLabel).join('/')})-人员申请详情`
            methods.getDetailTableList(true)
            params.cindex.value = i
        },

        addConfig: () => {
            params.settingList.value.push({
                AttrList: JSON.parse(JSON.stringify(params.sAttrList.value)),
                ProductCode: null,
                Remark: null
            })
            if (params.proxy.value?.$refs?.scrollt) {
                // 设置滚动条位置
                params.proxy.value.$refs.scrollt.scrollTop = 9999;
            } else {
                console.warn('scrollt ref 未找到，请检查 ref 绑定');
            }
        },
        delConfig: (i) => {
            params.settingList.value.splice(i, 1)
        },
        filterOption: (val, type) => {
            return `${type.label}`.includes(`${val || ''}`)
        },
        handleCancel: () => {
            params.uploadImg.value.previewVisible = false; 
            params.uploadImg.value.previewTitle = '';
        },
        getBase64: (file) => {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = () => resolve(reader.result);
                reader.onerror = error => reject(error);
            })
        },
        handlePreview: async (file) => {
            console.log(file, 'file')
            if (!file.url && !file.preview) {
                file.preview = (await methods.getBase64(file.originFileObj));
            }
            params.uploadImg.value.previewImage = file.url || file.preview;
            params.uploadImg.value.previewVisible = true;
            params.uploadImg.value.previewTitle = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
        },

        generatediker: (data) => {
            // 提取属性值和 ID 列表
            const valueLists = data.map(item =>
                item.ItemList.map(listItem => ({
                    name: listItem.AttributeValue,
                    id: listItem.Id,
                }))
            );

            // 生成笛卡尔积
            const cartesianProduct = (arrays) => {
                return arrays.reduce((acc, array) => {
                    return acc.flatMap((prev) => {
                        return array.map((value) => {
                            return [...prev, value];
                        });
                    });
                }, [[]]);
            };

            // 返回笛卡尔积的结果
            return cartesianProduct(valueLists);
        },

        enter: (index) => {
            params.cindex.value = index
        },

        handleDetailTableChange: (page) => {
            const { current, pageSize } = page
            params.detailPagination.value.current = current;
            params.detailPagination.value.pageSize = pageSize;
            methods.getDetailTableList()
        },

        IGetDepartmentApproverList: () => {

            Request({
                url: "/PPE/GetDepartmentApproverList",
                method: 'post',

            }).then(res => {
                params.checkPersonList.value = res.Data.map(e => ({ label: e.UserName, value: e.UserNo }))
                if (params.checkPersonList.value.length != 0) {
                    params.configData.value.checkPersonId = params.checkPersonList.value[0].value
                }
            })
        },

        getDetailTableList: (isRresh) => {
     

        },

        GetApplyFormNo: () => {
            Request({
                url: "/PPE/GetApplyFormNo",
                method: 'post',

            }).then(res => {
                params.configData.value.name1 = res.Data
            })

        },
        IGetProductCode: () => {
            return new Promise((resolve, rej) => {
                params.uploadLock.value=true
                Request({
                    url: "/PPE/GetProductCode",
                    method: 'post',
                    data: {
                        BasicId: params.urlparams.value.id
                    }

                }).then(res => {
                    resolve(res)
                    params.uploadLock.value = false
                })

            })
         

        },

        sumData: (Array, flag = true) => {

            let Sum = Array.reduce((Sum, currData) => {
                return Sum + currData.Quantity;
            }, 0)

            return Sum
        },

        importData: (i) => {
            const input = document.createElement('input');
            input.type = 'file';
            input.addEventListener('change', function (event) {
                const file = event.target.files[0];
                var formdata = new FormData()
                formdata.append('any', file)
                Request({
                    url: "/PPE/ImportEmpList",
                    method: 'post',
                    data: formdata
                }).then(res => {

                    params.messageTest.value.info(res.Msg);
                    params.editInfo.value[i].EmployeeList = [...params.editInfo.value[i].EmployeeList, ...res.Data]
                    params.editInfo.value[i].e = methods.sumData(params.editInfo.value[i].EmployeeList)

                })
            });
            input.click();

        },

        downloadTemplate: () => {
            params.uploadLock.value = true
            downloadfun('人员申请模板', '../File/Templete/PPE/劳防用品申请人员导入模板.xls').finally(() => {
                params.uploadLock.value = false

            })
         
        },
        onBack: () => {
            window.history.back() 
        },
        GetBasicList: () => {
   
            params.uploadLock.value = true
            Request({
                url: "/PPE/GetEquBasicInfo",
                method: 'post',
                params: {
                    Id: params.urlparams.value.id,
                },
            }).then(res => {
                params.baseInfo.value = res.Data

 
                params.sAttrList.value = res.Data.AttrList

                methods.IGetProductCode().then(fres => {
                    if (fres.Data.length == 0) {
                        params.settingList.value = [
                            {
                                AttrList: JSON.parse(JSON.stringify(params.sAttrList.value)),
                                ProductCode: null,
                                Remark: null
                            }]

                        params.settingList.value = params.settingList.value.map(e => {
                            return {
                                AttrList: JSON.parse(JSON.stringify(params.sAttrList.value)),
                                selected: [],
                                ProductCode: null,
                                Remark: null
                            }
                        })
                    } else {

                        params.settingList.value = fres.Data.map(e => {
                            return {
                                AttrList: JSON.parse(JSON.stringify(params.sAttrList.value.map((es,is) => {
                                    return {
                                        ...es,
                                        Selected: e.AttrList[is]
                                    }
                                }))),
                                selected: e.AttrList,
                                ProductCode: e.ProductCode,
                                Remark: e.Remark
                            }
                        })

                    }
            

                })




          


            }).finally(() => {
          
            })
        },
        onSubmit: () => {
        
            let obj = params.settingList.value.map(e => {
                return {
                    BasicId: params.urlparams.value.id,
                    AttrList: e.AttrList.filter(es => Boolean(es.Selected)).map(es => es.Selected),
                    ProductCode: e.ProductCode,
                    Remark: e.Remark
                }

            })

            if (obj.map(e => e.AttrList).some(es => es.length !== params.sAttrList.value.length)) {
                return params.messageTest.value.info('请检查是否有未填写的规格参数');
            }
     
            if (obj.filter(e => e.ProductCode).map(es => es.ProductCode).length !== obj.length) {
                return params.messageTest.value.info('请检查是否有未填写的用品编码');
            }
            params.uploadLock.value = true
            Request({
                url: "/PPE/AddProductCode",
                method: 'post',
                data: obj
            }).then(res => {
                //methods.IGetProductCode()
                params.messageTest.value.info(res.Msg);

                setTimeout(() => {
                    window.history.back()
                },600)
                
            })



    },
        init: () => {
            getBrowserInfo().catch(err => { console.log(err) })
            if (proxy) {
                params.proxy.value = proxy
            }
            const { message } = antd
            params.messageTest.value = message
            params.messageTest.value.config({
                top: `10vh`,
                duration: 7,
                maxCount: 1,
                rtl: true,
            });


            let info = Storage.get('AccountInfo', true)
            Request({
                url: "/Account/createJwtToken",
                method: 'post',
                data: {
                    "userName": info && info.UserNo
                }
            }).then(res => {
                methods.IGetDepartmentApproverList()
                let urlparams = queryURLParams()
                params.urlparams.value = urlparams
                params.TypeId.value = urlparams.type
                Storage.set('token', res.Data,true)
                methods.GetBasicList()
                methods.scrollt()
                //params.configData.value.name2 = `${info.UserName}(${info.UserNo})`
                //params.configData.value.name3 = dayjs(Date.now()).format('YYYY-MM-DD HH:mm')
                //params.configData.value.name4 = info.DepartmentName



                //methods.GetApplyFormNo()
                //methods.GetBasicList()



            })
        },

    }
    const template = {
        pdfPopModel: {
            template: `
           <a-modal v-model:open="pdfOpen" width = "80%" title = "PDF预览" v-on:ok="pdfOpen=false" >
<div style='height:700px'>
                <embed id="pdfviewscreen" :src="pdfurl" type="application/pdf" width="100%" style="height:100%;" />

</div>
  
            </a-modal >
`,
            setup() {
                return {
                    ...params,
                    ...methods,
                };
            }
        },




        bottomBtns: {
            template: `<div class="w-full bg-[#eeeeee] h-50  flex  items-center justify-end pr-4">
                    <a-space>


  <a-popconfirm
    title="确定执行此操作?"
    ok-text="确定"
    cancel-text="取消"
    @confirm="onSubmit(0)"
  >
 <a-button  :loading="uploadLock" type="dashed">保存</a-button>
  </a-popconfirm>

                        <a-button v-on:click="onBack" :loading="uploadLock">返回</a-button>
                    </a-space>
                </div>`,
            setup() {

                return {
                    ...params,
                    ...methods,
                };
            }

        }
    }
    return {
        ...params,
        ...methods,
        template
    }
}
export default Composition